<template>
	<view class="conents">
		<view class="map" id="amap" ref="amap"></view>
		<u-navbarmap :height="60" :autoBack="false">
			<template #center>
				<view class="searchbtn" @click="gosearchStationCar">
					<view class="placeholder">{{$z.$t("查找电站")}}</view>
					<view class="iconfont icon-fangdajing"></view>
				</view>
			</template>
			<template #left>
				<view class="u-flex" style="font-weight: bold" @click="getwz">
					<text class="u-line-1" style="width: 100rpx; margin-right: 8rpx">
						{{city}}
					</text>
					<u-icon name="arrow-down"></u-icon>
				</view>
			</template>
			<template #right>
				<view class="iconfont icon-shaixuan" @click="sxfn"></view>
			</template>
		</u-navbarmap>
		<view class="bottonbox">

			<view class="wzitem iconfont icon-dingwei1" @click="wzitemtap"></view>
			<caritem :item="showitem" v-if="showitem.id && showitem.id != -1"></caritem>
		</view>
		<pt ref="pt" @save="save"></pt>
		<ztabbar></ztabbar>
		<view :mapOverlays="mapOverlays" :change:mapOverlays="aMapRenderJs.getmarkers"></view>
	</view>
</template>
<script>
	import config from "@/config/index.js"
	// import dwimg from "@/static/map/dw.png"
	// #ifdef APP
	// let dwimg = `${config.baseURL}/wxhtml/img/default-40x40.png`
	//#endif
	import pt from "./components/pt.vue";
	import qs from "qs"

	import cityjs from "@/pages/city/cityjs.js";
	console.log(cityjs);
	export default {
		components: {
			pt
		},
		data() {
			return {
				center: {
					lat: 30.30593658246207,
					lng: 120.17779051925028,
				},
				zoom: 15,
				wzlist: [],
				ptlist: [],
				list: [],
				showitem: {},
				latitude: "39.909",
				longitude: "116.39742",

				// dwimg,
				title: "充电桩",
				query: {},
				wz: {
					lng: "116.39742",
					lat: "39.909"
				},
				ChargeCarRange: [],

				popupshow: false,
				activeChargeCar: {}
			}
		},
		mounted() {
			this.init()
		},
		onLoad(query) {
			this.query = query;
		},
		onShow() {
			// this.init()
		},
		computed: {
			city() {
				if (this.$store.state.config.city.label) {
					return this.$store.state.config.city.label;
				}
				if (this.wzlist.length == 0) {
					return "";
				}
				let cityjsxs = cityjs.flat();
				let r = cityjsxs.find((e) => {
					return e.value == this.wzlist[0].AreaCode;
				});
				return r ? r.label : "";
			},
			showlist() {
				let ptlist = this.$u.deepClone(this.ptlist);
				let showlist = this.list.filter((e) => {
					if (ptlist.length == 0) {
						return true;
					}
					let kmclist = ptlist.filter((e) => {
						return e == this.$z.$t("快充") || e == this.$z.$t("慢充");
					});
					if (kmclist.length == 1) {
						let kmclista = [{
								name: this.$z.$t("快充"),
								value: "carzlsum",
							},
							{
								name: this.$z.$t("慢充"),
								value: "carjlsum",
							},
						];
						let kmclistb = kmclista.filter((e) => {
							return kmclist.indexOf(e.name) > -1;
						});
						if (e[kmclistb[0].value] == 0) {
							return false;
						}
					}
					let par1 = e.par1.split(",").filter((e) => {
						return e != "";
					});
					let par2 = ptlist.filter((e) => {
						return e != this.$z.$t("快充") && e != this.$z.$t("慢充");
					});
					if (par2.length == 0) {
						return true;
					}
					return par2.every((e) => {
						return par1.includes(e);
					});
				});

				// this.wz = {
				// 	lng: wz2[0],
				// 	lat: wz2[1]
				// }
				showlist = showlist.map(e => {
					let mpt = e.mpt || "";
					mpt = mpt.match(/\d+\.\d+/g);
					let wz2 = uni.$z.gps.bd09togcj02(mpt[0], mpt[1]);
					e.mapmpt = {
						lat: wz2[1],
						lng: wz2[0],
					}
					e.active = e.id == this.showitem.id
					return e
				})

				return showlist;
			},
			reqsearchdata() {
				let r = {};
				if (this.$store.state.config.city.value) {
					r.AreaCode = this.$store.state.config.city.value;
				} else {
					let wz = this.$store.state.config.wz;
					r.pt = `POINT(${wz.lng},${wz.lat})`;
				}

				return r;
			},
			mapOverlays() {
				return {
					showlist: this.showlist,
					latitude: this.latitude,
					longitude: this.longitude
				}
			}

		},
		methods: {
			async df(item) {
				let StationHD = await this.$store.dispatch("request/getRequest", {
					url: "/StationHD",
					data: {
						id: item.id,
					},
				});
				if (StationHD.length == 0) {
					return "0";
				}
				if (StationHD[0].type == "1") {
					return Number(StationHD[0].df).div(100);
				}
				let StationCar = item;

				let dfarr1 = [
					[{
							label: this.$z.$t("尖峰"),
							value: "jdf",
						},
						{
							label: this.$z.$t("尖峰服务费"),
							value: "jfff",
						},
						["jsjsh", "jsjsm", "jsjeh", "jsjem"],
					],
					[{
							label: this.$z.$t("高峰"),
							value: "fdf",
						},
						{
							label: this.$z.$t("高峰服务费"),
							value: "ffff",
						},
						["fsjsh", "fsjsm", "fsjeh", "fsjem"],
					],
					[{
							label: this.$z.$t("平峰"),
							value: "pdf",
						},
						{
							label: this.$z.$t("平峰服务费"),
							value: "pfff",
						},
						["psjsh", "psjsm", "psjeh", "psjem"],
					],
					[{
							label: this.$z.$t("谷峰"),
							value: "gdf",
						},
						{
							label: this.$z.$t("谷峰服务费"),
							value: "gfff",
						},
						["gsjsh", "gsjsm", "gsjeh", "gsjem"],
					],
				];
				let times = [];
				dfarr1.forEach((e) => {
					let je1 = StationCar[e[0].value] / 100;
					let je2 = StationCar[e[1].value] / 100;
					let je3 = Number(StationCar[e[0].value])
						.add(Number(StationCar[e[1].value]))
						.div(100);

					let dsstr = "";
					for (let i = 1; i <= 5; i++) {
						let t1 = StationCar[`${e[2][0]}${i}`];
						let t2 = StationCar[`${e[2][1]}${i}`];
						let t3 = StationCar[`${e[2][2]}${i}`];
						let t4 = StationCar[`${e[2][3]}${i}`];
						if (!t1) {
							t1 = "0";
						}
						if (!t2) {
							t2 = "0";
						}
						if (!t3) {
							t3 = "0";
						}
						if (!t4) {
							t4 = "0";
						}
						t1 = t1 < 10 ? "0" + t1 : t1;
						t2 = t2 < 10 ? "0" + t2 : t2;
						t3 = t3 < 10 ? "0" + t3 : t3;
						t4 = t4 < 10 ? "0" + t4 : t4;

						if (!(t1 == 0 && t2 == 0 && t3 == 0 && t4 == 0)) {
							dsstr = t1 + ":" + t2 + "--" + t3 + ":" + t4;
							times.push([
								...e,
								{
									t1: `${t1}:${t2}`,
									t2: `${t3}:${t4}`,
									je1,
									je2,
									je3,
								},
							]);
						}
					}
				});
				// this.fys = times;
				let dqt = this.$z.timefn.gettime(0, new Date(), `hh:MM`);
				let dqtimes = times.findIndex((e) => {
					let h = dqt.split(":")[0];
					let M = dqt.split(":")[1];
					let h1 = e[3].t1.split(":")[0];
					let M1 = e[3].t1.split(":")[1];
					let h2 = e[3].t2.split(":")[0];
					let M2 = e[3].t2.split(":")[1];
					// 转数字
					h = Number(h);
					M = Number(M);
					h1 = Number(h1);
					M1 = Number(M1);
					h2 = Number(h2);
					M2 = Number(M2);
					return (
						(h1 < h && h < h2) || (h1 == h && M1 <= M) || (h2 == h && M2 >= M)
					);
				});
				if (dqtimes == "-1") {
					return "0";
				}
				// this.dqi = dqtimes;
				return times[dqtimes][3].je3;
			},

			save(list) {
				this.ptlist = list;
			},
			async wzitemtap() {
				if (Object.keys(this.$store.state.config.wz).length == 0) {
					await this.$store.dispatch("config/getLocation");
				}
				this.latitude = this.wz.lat + 0.00001
				this.longitude = this.wz.lng + 0.00001
				setTimeout(() => {
					this.latitude = this.wz.lat
					this.longitude = this.wz.lng
				})
				this.center = {
					...this.$store.state.config.wz,
				};
				this.showitem.id = -1;
				this.zoom = 15
			},
			gosearchStationCar() {
				uni.navigateTo({
					url: "/pages/searchStationCar/searchStationCar",
				});
			},
			getwz() {
				uni.navigateTo({
					url: "/pages/city/city",
				});
			},
			sxfn() {
				this.$refs.pt.show();
			},

			dwimgtap() {
				delete this.activeChargeCar.gtel
				this.latitude = this.wz.lat + 0.00001
				this.longitude = this.wz.lng + 0.00001
				setTimeout(() => {
					this.latitude = this.wz.lat
					this.longitude = this.wz.lng
				})

			},
			ChargeCarxqfn() {
				this.$refs.chargecarxq.init(this.activeChargeCar)

			},
			cdfn() {
				uni.navigateTo({
					url: `/pages/ChargeCarsys/ChargeCarsys?gtel=${this.activeChargeCar.gtel}`
				})
			},
			daohang() {
				let wz = this.activeChargeCar?.wz.match(/\(([^)]+)\)/);
				wz = wz[1].split(" ");
				uni.openLocation({
					latitude: Number(wz[1]),
					longitude: Number(wz[0]),
					success: function() {}
				});
			},
			setactiveChargeCar(item) {
				this.activeChargeCar = item
				let wz = this.activeChargeCar?.wz.match(/\(([^)]+)\)/);
				wz = wz[1].split(" ");
				this.latitude = wz[1]
				this.longitude = wz[0]
			},

			async wzinit() {
				console.log("wzinit");
				await this.init();
				let city = this.$store.state.config.city;
				if (city.wz) {

					this.latitude = city.wz[1]
					this.longitude = city.wz[0]
					console.log(this.longitude, this.latitude);
				}

			},
			async init() {
				if (Object.keys(this.$store.state.config.wz).length == 0) {
					console.log(222);
					await this.$store.dispatch("config/getLocation");
				}
				this.center = {
					...this.center,
					...this.$store.state.config.wz,
				};
				let wz2 = uni.$z.gps.bd09togcj02(this.center.lng, this.center.lat);
				this.wz = {
					lng: wz2[0],
					lat: wz2[1]
				}
				this.latitude = this.wz.lat
				this.longitude = this.wz.lng
				let list = await this.$z.request("/StationCar", this.reqsearchdata);
				for (let i = 0; i < list.length; i++) {
					list[i].df = await this.df(list[i])
				}
				this.list = list
				this.wzlist = this.$u.deepClone(list);
			},
			itemtap(item) {
				this.latitude = item.mapmpt.lat
				this.longitude = item.mapmpt.lng

				this.showitem = {
					...item
				}
			},
		}
	}
</script>
<script module="aMapRenderJs" lang="renderjs">
	import store from "@/store/index.js"
	export default {
		data() {
			return {
				// dwimg,
				showitem: {},
				map: "",
				amapOverlays: {},
				zoom: 15,
				amapactiveChargeCar: {},
				circle: [],
				markers: []
			}
		},
		mounted() {
			this.aMapinit()
		},
		computed: {
			watchmap() {
				return [this.map, this.amapOverlays]
			}
		},
		watch: {
			watchmap() {
				this.Overlaysinit()
			}
		},
		methods: {

			glztfn(data) {
				let lr = 0;
				for (let i = 1; i <= data.gls; i++) {
					if (data[`glzt${i}`] && data[`glzt${i}`]) {
						lr++
					}
				}
				return lr;
			},
			aMapinit() {
				if (typeof window.AMap === 'function') {
					this.initAmap();
				} else {

					// window._AMapSecurityConfig = {
					// 	securityJsCode: A_MAP_SECRET_KEY,
					// };
					const script = document.createElement('script');
					script.src =
						`https://maps.googleapis.com/maps/api/js?key=AIzaSyB6uNFNJWPMLLwO6_MF2FP4E4xO4ez0gPY&callback=console.debug&libraries=maps,marker&v=beta&libraries=marker`
					script.onload = this.initAmap.bind(this);
					document.head.appendChild(script);
				}
			},
			kxtd(item) {
				try {
					let num = Number(item.carzlsum)
						.add(item.carjlsum)
						.subtr(item.carzlsumcd)
						.subtr(item.carjlsumcd);
					return num;
				} catch {
					return "0";
				}
			},

			async buildContent(data = {}) {
				const content = document.createElement("div");
				content.classList.add("goodlemarker");
				if (data.active) {
					content.classList.add("active");
				}
				let df = data.df
				content.innerHTML = `
				<div class="kx">
					<div class="text">${this.kxtd(data)}</div>	
					<div class="text">leisure</div>
				</div>
				<div class="je">${df+`Units per degree`}</div>
			    `;
				return content;
			},
			async initAmap() {
				const {
					Map
				} = await google.maps.importLibrary("maps");
				const {
					AdvancedMarkerElement
				} = await google.maps.importLibrary("marker");
				this.map = new Map(document.getElementById("amap"), {
					center: new google.maps.LatLng(39.90923, 116.397428),
					zoom: 14,
					mapId: "4504f8b37365c3d0",
					clickableIcons: false,
					showMapPoi: false,
					disableDefaultUI: true,
				});

			},
			getmarkers(mapOverlays) {
				this.amapOverlays = mapOverlays;
			},
			async Overlaysinit() {
				if (this.map == "" || !this.amapOverlays) {
					return
				}

				this.map.setCenter(new google.maps.LatLng(this.amapOverlays.latitude, this.amapOverlays
					.longitude)); //同时设置地图层级与中心点


				const {
					AdvancedMarkerElement
				} = await google.maps.importLibrary("marker");
				this.markers.forEach(e => {
					e.setMap(null);
				})
				this.markers = []
				this.amapOverlays.showlist.forEach(async (e) => {
					let content = await this.buildContent(e)
					const marker = new AdvancedMarkerElement({
						map: this.map,
						position: e.mapmpt,
						content: content,
					});
					marker.addListener("click", () => {
						this.showitem = {
							...e
						}
						this.$ownerInstance.callMethod('itemtap', e)
						// console.log(this.showitem, "123");
					});
					this.markers.push(marker)
				})

				// marker.setMap(null)
			},

		}
	}
</script>

<style lang="scss" scoped>
	// ::v-deep .amap-logo {
	// 	display: none !important;
	// }

	// ::v-deep .amap-copyright {
	// 	display: none !important;
	// }

	.conents {
		display: flex;
		flex-direction: column;
		height: 100vh;

		.map {
			height: 100vh;
			width: 100%;
			position: relative;
		}
	}

	.dwimg {
		position: absolute;
		right: 20rpx;
		top: 168rpx;
		width: 32px;
		background: rgba(255, 255, 255, 1);
		height: 32px;
		cursor: pointer;
		// background-image: url(http://img.gpsserver.cn:20080/wxhtml/img/default-40x40.png);
		background-size: 20px 20px;
		background-repeat: no-repeat;
		background-position: center center;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;

		.img {
			width: 20px;
			height: 20px;
		}
	}

	.card {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		border-top-left-radius: 15px;
		border-top-right-radius: 15px;
		z-index: 9999;

		.card-footer {
			display: flex;
			align-items: center;
			padding: 10px 20px;
			padding-bottom: calc(10px + env(safe-area-inset-bottom));
			justify-content: space-between;
			color: #333;

			.btn {
				border: 1px solid #2093f5;
				color: #2093f5;
				display: flex;
				align-items: center;
				padding: 10rpx 20rpx;
				border-radius: 40rpx;
			}

			.xqbtn {
				padding: 10rpx 20rpx;
			}
		}

		.card-header {
			// display: flex;
			padding: 18px 14px;
			position: relative;
			// border: 2px solid #000000;
			// box-sizing: border-box;

			.t {
				font-size: 18px;
				font-weight: 600;
				color: #0e0e0e;
				display: block;
			}

			.b {
				font-size: 12px;
				margin-top: 9px;
				color: #2c2c2c;
				line-height: 1.2;
			}

			&::after {
				position: absolute;
				bottom: 0px;
				right: 0;
				left: 0;
				height: 1px;
				content: '';
				transform: scaleY(.5);
				background-color: #eee;
			}
		}
	}

	.searchbtn {
		width: 400rpx;
		background-color: #fff;
		height: 80rpx;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.iconfont {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: $u-primary;
			font-size: 40rpx;
		}

		.placeholder {
			font-size: 28rpx;
			color: $uni-text-color-placeholder;
			padding-left: 20rpx;
		}
	}

	.icon-shaixuan {
		background: #fff;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10rpx;
		color: $uni-color-primary;
	}

	.bottonbox {
		position: fixed;
		bottom: 0;
		padding: 0 30rpx;
		padding-bottom: 160rpx;

		left: 0;
		right: 0;

		.wzitem {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
			font-size: 50rpx;
			background: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 20rpx;
		}
	}
</style>